package com.example.vote.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.vote.model.User;
import com.example.vote.service.UserService;
import com.example.vote.utils.Constant;
import com.example.vote.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * ClassName: UserController
 * Package: com.example.vote.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-06-21
 * Time: 11:13
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //在使用BCryptPasswordEncoder之前 要在配置类中@Bean注入BCryptPasswordEncoder
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //登录请求
    /**
     * 请求
     * post，
     * /user/login
     * data:{username,password}
     */

    /**
     * 响应
     * "status":0,
     * "message":"登录成功",
     * "data":{
     *     "id":****,
     *     "username":****,
     *     "password":****
     * }
     */
    @PostMapping("/login")
    public Result<User> login(String username,
                              String password,
                              HttpServletRequest request,
                              HttpServletResponse response) throws IOException {
        //先去查用户名 存在用户 在对比密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",username);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            return new Result<>(-1,"用户名不存在",null);
        }

        //bCryptPasswordEncoder.encode(); 这个是加密 encode编码
        //matches 比对 第一个参数是普通密码 第二个参数是加密的密码
        boolean matches = bCryptPasswordEncoder.matches(password,user.getPassword());
        //不为空 对比密码 字符串对比 equals
        if (!matches){
            //密码不正确
            return new Result<>(-1,"密码错误",null);
        }

        //判断身份scale 1表示管理员 2表示普通用户
        if (user.getScale() == 1){
            //管理员

            //登录成功之后 存入Session
            HttpSession session = request.getSession(true);

            //key值定义为静态不变常量
            session.setAttribute(Constant.USERINFO_SESSION_ADMIN,user);
            //重定向 对5个表的增删改查
            //response.sendRedirect("/adminList.html");
        }else if (user.getScale() == 2){
            //普通用户

            //登录成功之后 存入Session
            HttpSession session = request.getSession(true);

            //key值定义为静态不变常量
            session.setAttribute(Constant.USERINFO_SESSION_KET,user);

            System.out.println(session.getAttribute(Constant.USERINFO_SESSION_KET) + "123");

            //重定向 user.html 进去就是投票界面
            //response.sendRedirect("/index.html");
        }
        return new Result<>(0,"登录成功",user);
    }

    //查找用户请求
    /**
     * get user/find
     */
    @GetMapping("/find")
    public Result<List<User>> find(@RequestParam(required = false) String name){
        //支持模糊查询
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (name != null){
            queryWrapper.like("account",name);
            list = userService.list(queryWrapper);
        }else {
            list = userService.list();
        }

        return new Result<>(1,"查找成功",list);
    }


    //删除用户
    @PostMapping("/delete")
    public Result<Boolean> delete(Integer id){

        System.out.println(id);
        boolean ret = userService.removeById(id);
        System.out.println(ret);

        if (ret){
            return new Result<Boolean>(1,"删除成功",ret);
        }
        return new Result<>(0,"删除失败",false);
    }

    //添加用户
    @PostMapping("/add")
    public Result<Boolean> add(String username,String password){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getAccount,username);

        User user = userService.getOne(queryWrapper);

        if (user != null){
            //表示用户名存在 添加失败
            return new Result<>(0,"用户名已存在",false);
        }

        User user1 = new User();
        user1.setAccount(username);
        user1.setPassword(bCryptPasswordEncoder.encode(password));
        //默认新增 普通用户
        user1.setScale(2);

        boolean ret = userService.save(user1);

        if (ret){
            return new Result<>(1,"新增成功",ret);
        }

        return new Result<>(0,"新增失败",false);

    }

    //修改用户
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody User user){
        boolean ret = userService.updateById(user);
        if (ret){
            return new Result<>(1,"修改成功",ret);
        }

        return new Result<>(0,"修改失败",false);
    }


    //
    @GetMapping("/userInfo")
    public Result<User> userIndo(HttpServletRequest req){
        // 从 session 中拿到用户信息
        HttpSession session = req.getSession(false);
        if (session == null) {
            return null;
        }
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KET);
        if (user == null) {
            return null;
        }
        return new Result(1,"获取成功",user);
    }

}
